package com.lixin.springcloud.controller;

import com.lixin.springcloud.entities.CommonResult;
import com.lixin.springcloud.entities.Payment;
import com.lixin.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String port;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("插入结果：{}", result);
        if (result <= 0) {
            return new CommonResult<>(10000, "插入失败", null);
        }
        return new CommonResult<>(20000, "插入成功 port：" + port, payment);
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("查询成功：{}", payment);
        if (payment == null) {
            return new CommonResult<>(10000, "查询失败 port：" + port, null);
        }
        return new CommonResult<>(20000, "查询成功 port：" + port, payment);
    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("service：{}", service);
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances) {
                log.info("instanceId:{} instanceHost:{} instancePort:{} instanceUri:{}",
                        instance.getInstanceId(), instance.getHost(), instance.getPort(), instance.getUri());
            }
        }
        return discoveryClient;
    }

    // 用于测试调用超时
    @GetMapping("/payment/timeout")
    public String paymentTestTimeout() {
        return paymentService.testHystrix();
    }

}
